<template>
  <div class="post">
    <el-form :inline="true" :model="formData" :rules="rules" ref="formData">
      <el-form-item label="帖子标题" prop="postTitle">
        <el-input
          v-model="formData.postTitle"
          placeholder="帖子标题"
          autocomplete="off"
          :clearable="true"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
        <el-button type="primary" @click="dialogFormVisible = true"
          >添加帖子</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 添加帖子 -->
    <el-dialog
      title="添加帖子"
      width="40%"
      :visible.sync="dialogFormVisible"
      @close="closeDialog"
    >
      <el-form
        :model="insertForm"
        :rules="insertRules"
        ref="insertForm"
        class="insertForm"
      >
        <el-form-item
          label="帖子标题"
          prop="postTitle"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="insertForm.postTitle"
            placeholder="帖子标题"
            autocomplete="off"
            :clearable="true"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="帖子内容"
          prop="content"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="insertForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入内容"
            autocomplete="off"
            maxlength="500"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="insert" :loading="insertLoading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 表格 -->
    <div class="admin-table">
      <div class="batch-btn">
        <el-button
          type="danger"
          size="mini"
          @click="batchDelete"
          v-show="this.multipleSelection.length > 0"
          >批量删除</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="tableLoading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="46" align="center">
        </el-table-column>
        <el-table-column
          type="index"
          width="50"
          :index="indexConfig"
          label="序号"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="postTitle"
          label="帖子名称"
          width="300"
          align="center"
        >
        </el-table-column>
        <el-table-column label="发布者" width="200" align="center">
          <template slot-scope="scope">
            <span
              :style="{
                color: scope.row.identity === 2 ? '#F56C6C' : '#888',
              }"
              >{{ scope.row.userName }}</span
            >
          </template>
        </el-table-column>
        <el-table-column label="发布时间" width="180" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="修改时间" width="180" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="edit(scope.row)"
              >编辑</el-button
            >
            <el-button type="primary" size="mini" @click="remark(scope.row)"
              >查看评论</el-button
            >
            <el-button type="danger" size="mini" @click="del(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        v-show="tableData.length > 0"
        background
        layout="prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="handleCurrentChange"
        :pager-count="7"
        style="text-align: right; margin-top: 24px"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getPostList, insertPost, batchDeletePost } from "@/api/admin/post";
export default {
  name: "PostView",
  data() {
    return {
      formData: {
        postTitle: "",
      },
      insertForm: {
        postTitle: "",
        identity: "admin",
        content: "",
      },
      rules: {
        postTitle: [{ validator: this.customValidator, trigger: "blur" }],
      },
      insertRules: {
        postTitle: [
          { required: true, message: "请输入帖子标题", trigger: "blur" },
        ],
        content: [
          { required: true, message: "请输入帖子内容", trigger: "blur" },
        ],
      },
      page: 1,
      pageSize: 8,
      total: 0,
      currentPage: 1,
      dialogFormVisible: false,
      insertLoading: false,
      formLabelWidth: "120px",
      // 表格
      tableData: [],
      tableLoading: false,
      multipleSelection: [],
    };
  },
  created() {
    this.getDataList();
  },
  methods: {
    // 自定义校验规则
    customValidator(rule, value, callback) {
      const { postTitle } = this.formData;
      if (!postTitle) {
        callback(new Error("请填写信息"));
      } else {
        callback();
      }
    },
    // 查询
    query() {
      this.$refs.formData.validate((v) => {
        if (v) {
          this.page = 1;
          this.getDataList();
        }
      });
    },
    // 清空
    clear() {
      this.page = 1;
      this.currentPage = 1;
      // 清空表单
      this.$refs.formData.resetFields();
      this.getDataList();
    },
    // 新增
    insert() {
      this.$refs.insertForm.validate(async (v) => {
        if (v) {
          try {
            // 转换格式
            this.insertForm.content = this.insertForm.content
              .replace(/\r\n/g, "<br/>")
              .replace(/\n/g, "<br/>")
              .replace(/\s/g, " ");
            this.insertLoading = true;
            const res = await insertPost(this.insertForm);
            this.dialogFormVisible = false;
            await this.getDataList();
          } finally {
            this.insertLoading = false;
          }
        }
      });
    },
    // 关闭新增对话框的操作
    closeDialog() {
      this.insertLoading = false;
      this.$refs.insertForm.resetFields();
    },
    // 获取帖子列表
    async getDataList() {
      try {
        this.tableLoading = true;
        const res = await getPostList({
          ...this.formData,
          page: this.page,
          pageSize: this.pageSize,
        });
        this.tableData = res.data.records;
        this.total = res.data.total;
      } finally {
        this.tableLoading = false;
      }
    },
    // 配置表格索引
    indexConfig(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },
    // 当选项发生变化触发
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 分页查询
    handleCurrentChange(page) {
      this.page = page;
      this.currentPage = page;
      this.getDataList();
    },
    // 时间格式判断
    padZero(num) {
      return num < 10 ? "0" + num : num;
    },
    // 时间格式化
    formatDate(timeArray) {
      if (!timeArray) return "暂无时间";
      let year = timeArray[0];
      let month = this.padZero(timeArray[1]);
      let day = this.padZero(timeArray[2]);
      let hour = this.padZero(timeArray[3]);
      let minute = this.padZero(timeArray[4]);
      let second = this.padZero(timeArray[5]) || "00";
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
    // 编辑
    edit(row) {
      // 可以依然跳转到layout中的router-view中
      this.$router.push({
        name: "AdminEditPost",
        params: { id: row.id },
      });
    },
    // 查看评论
    remark(row) {
      this.$router.push({
        name: "AdminPostRemark",
        params: { id: row.id },
      });
    },
    // 删除
    async del(row) {
      this.$confirm(
        "确定删除所选数据吗？这将会删除对应的帖子评论信息，请谨慎操作！",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(async () => {
        try {
          this.tableLoading = true;
          const res = await batchDeletePost([row.id]);
          await this.getDataList();
        } finally {
          this.tableLoading = false;
        }
      });
    },
    // 批量删除
    async batchDelete() {
      const ids = [];
      this.multipleSelection.forEach((item) => {
        ids.push(item.id);
      });
      this.$confirm(
        "确定删除所选数据吗？这将会删除对应的帖子评论信息，请谨慎操作！",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(async () => {
        try {
          this.tableLoading = true;
          const res = await batchDeletePost(ids);
          await this.getDataList();
        } finally {
          this.tableLoading = false;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.post {
  width: 100%;
  height: 100%;
  background-color: #fff;
  .insertForm {
    width: 500px;
  }
  .admin-table {
    .batch-btn {
      height: 28px;
      margin-bottom: 4px;
    }
  }
}
/*
解决单选框样式问题
  Blocked aria-hidden on an element because its descendant retained focus. 
  The focus must not be hidden from assistive technology users. 
  Avoid using aria-hidden on a focused element or its ancestor. 
  Consider using the inert attribute instead, which will also prevent focus. 
  For more details, see the aria-hidden section of the WAI-ARIA specification at Element with focus: input Ancestor with aria-hidden:
*/
/deep/ input[aria-hidden="true"] {
  display: none !important;
}
/deep/.el-radio:focus:not(.is-focus):not(:active):not(.is-disabled)
  .el-radio__inner {
  box-shadow: none !important;
}
</style>